package com.orjl.networkj;

import android.util.Log;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import okio.BufferedSink;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

/**
 * 版权： 版权所有
 * <p>
 * 作者：suntinghui
 * <p>
 * 创建日期：2019/5/20 0020 15:25
 * <p>
 * 描述：
 * <p>
 *  RestSource.getApiService().getTangPoetry(1,10)
 *       .subscribeOn(Schedulers.io())
 *       .doOnSubscribe(new Consumer<Disposable>() {
 *
 *    @Override
 *    public void accept(Disposable disposable) throws Exception {
 *    }
 *    }).observeOn(AndroidSchedulers.mainThread())
 *       .subscribe(new BaseObserver<List<>>(this) {
 *    @Override
 *    public void onSuccess(List<> tangPoetryResponseModels) {
 *        if (tangPoetryResponseModels != null&&tangPoetryResponseModels.size()>0) {
 *           Toast.makeText(MainActivity.this, tangPoetryResponseModels.get(0).content, Toast.LENGTH_SHORT).show();
 *        }
 *     }
 *    });
 *
 *
 * <p>
 * 修订历史：
 */


public class RestSource {
    private static ApiService apiService;


    public static ApiService getApiService() {

        if (apiService == null) {
            synchronized (RestSource.class) {
                if (apiService == null) {

                    HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLogger()).setLevel(HttpLoggingInterceptor.Level.BODY);

                    OkHttpClient okHttpClient;
                    okHttpClient = new OkHttpClient.Builder()
                            .retryOnConnectionFailure(true)
                            .readTimeout(30000, TimeUnit.SECONDS)
                            .connectTimeout(30000, TimeUnit.SECONDS)
                            .writeTimeout(30000, TimeUnit.SECONDS)
                            .addInterceptor(httpLoggingInterceptor)
                            .addInterceptor(new Interceptor() {
                                @Override
                                public Response intercept(Chain chain) throws IOException {
                                    return chain.proceed(formatRequest(chain.request()));
                                }
                            })
                            .build();


                    Retrofit retrofit = new Retrofit.Builder()
                            .baseUrl(Constants.BASEURL)
                            .client(okHttpClient)
                            .addConverterFactory(CustomGsonConverterFactory.create())
                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                            .build();

                    apiService = retrofit.create(ApiService.class);
                }
            }
        }
        return apiService;

    }

    private static Request formatRequest(Request request) {
        Request.Builder builder = request.newBuilder();
//
//       builder.addHeader("content-type", "text/html;charset=UTF-8");
        return builder.url(request.url()).build();
    }


    public static class HttpLogger implements HttpLoggingInterceptor.Logger {
        private StringBuilder mMessage = new StringBuilder();

        @Override
        public void log(String message) {
            // 请求或者响应开始
            if (message.startsWith("--> POST")) {
                mMessage.setLength(0);
            }
            if (message.startsWith("param=")) {
                message = message;
            }
            // 以{}或者[]形式的说明是响应结果的json数据，需要进行格式化
            if ((message.startsWith("{") && message.endsWith("}"))
                    || (message.startsWith("[") && message.endsWith("]"))) {
                message = JsonUtil.formatJson(message);
            }
            mMessage.append(message.concat("\n"));
            // 请求或者响应结束，打印整条日志
            if (message.startsWith("<-- END HTTP")) {
                Log.d("networkj", mMessage.toString());
            }
        }
    }
}
